<template>
  <div class="wrapper">
    通告主信息
    <FormPanel
      ref="infoMain"
      :list="formList"
      :formType="type"
      @formChange="changeHandle"
      :isSubmitBtn="false"
    />
    <div>
      主要内容
      <FormPanel
        ref="infoMain1"
        :list="formList1"
        :formType="type"
        @formChange="changeHandle2"
        :isSubmitBtn="false"
      />
      <tinymce
        v-model="content"
        :height="300"
        :disabled="isReadOnly"
        :isUploadImage="false"
        actionUrl="/api/file/oss/upload"
      />
    </div>
    <div>
      附件上传
      <FormPanel
        ref="infoFile"
        :list="form"
        :formType="type"
        @formChange="changeHandleFile"
        :isSubmitBtn="false"
      />
    </div>
    <!-- <div v-show="isShow">
    车厂用户角色
    <FilterTable
      height="300"
      ref="oemRoleTable"
      :columns="oemRoleColumns"
      :dataSource="listOemRole"
      :isSelectColumn="isSelectColumn"
      :datakey="'records'"
      :onColumnsChange="oemRoleColumns => this.oemRoleColumns = oemRoleColumns"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="roleHeader">添加</el-button>
      </template>
    </FilterTable>
    </div>-->
    <!-- <div v-show="isShow">
    下发经销商
    <FilterTable
      height="300"
      ref="dealerTable"
      :columns="dealerColumns"
      :dataSource="listDealer"
      :isSelectColumn="isSelectColumn"
      :datakey="'records'"
      :onColumnsChange="dealerColumns => this.dealerColumns = dealerColumns"
    >
      <template slot="controls" >
        <el-button size="small" type="primary" icon="el-icon-plus" @click="dealerHeader">添加</el-button>
      </template>
    </FilterTable>
    </div>-->
    <div>
      <!-- table -->
      <div v-show="isShow">
        经销商角色属性
        <FilterTable
          height="300"
          ref="dealerRoleTable"
          :columns="dealerRoleColumns"
          :dataSource="listDealerRole"
          :isSelectColumn="isSelectColumn"
          :datakey="'records'"
          :onColumnsChange="dealerRoleColumns => this.dealerRoleColumns = dealerRoleColumns"
        >
          <template slot="controls">
            <el-button size="small" type="primary" icon="el-icon-plus" :disabled="this.value.type === 'show' ?true:false" @click="dealerRoleHeader">添加</el-button>
          </template>
        </FilterTable>
      </div>
    </div>

    <!-- 角色选择弹窗 -->
    <BaseDialog
      title="车厂角色选择"
      :visible.sync="visibleOemRole"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <oem-role v-if="visibleOemRole" ref="addOemRole" @close="closeOemRole" />
    </BaseDialog>

    <!-- 经销商选择弹窗 -->
    <BaseDialog
      title="经销商选择"
      :visible.sync="visibleDealer"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-model
        v-if="visibleDealer"
        ref="addDealer"
        selectType="multiple"
        v-model="initDealerData"
        @close="closeDealer"
      />
    </BaseDialog>

    <!-- 经销商角色属性选择弹窗 -->
    <BaseDialog
      title="经销商角色属性"
      :visible.sync="visibleDealerRole"
      width="1000px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <dealer-role ref="addDealer" v-model="initDealerRoleData" @close="closeRoleDealer" />
    </BaseDialog>

    <div class="dialogBottmView" :style="{position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'}"
      >
      <el-button @click="closeDialog()">取 消</el-button>
      <el-button
        v-show="this.value.type === 'show' ?false:true"
        @click="publishDialog"
        :disabled="isAddPub"
        type="primary"
      >发 布</el-button>
      <el-button
        v-show="this.value.type === 'show' ?false:true"
        @click="saveDialog"
        :disabled="isAdd"
        type=""
      >保 存</el-button>
    </div>
  </div>
</template>

<script>
import { authority } from '@/utils/authMixin';
import { dictionary } from '@/utils/dictMixin';
import { addNotification, getNotificationById, updateNotification, publishNotification, putNotification } from '@/api/admin/notice/dcsNoticeMaintain/index';
import dealerModel from './dealerdata';
import dealerRole from './dealerRole';
import oemRole from './oemRole';
import { getComOrgTreeList,getComOrgTreeLists} from '@/api/common/org/employeeInfo';
import { getJsonTree } from '@/utils/index';
import { IDNumber, phone, endTime, email, formatDates, checkPassport } from '@/utils/validate';
export default {
  mixins: [authority, dictionary],
  components: {
    dealerModel,
    dealerRole,
    oemRole
  },
  props: {
    value: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      formList: this.createFormList(),
      formList1: this.createFormList1(),
      form: this.createForm(),
      type: this.value.type,
      notificationId: this.value.type === 'edit' ? this.value.notificationId : this.value.type === 'show' ? this.value.notificationId : null,
      oemRoleColumns: this.creatHeader4OemRoleColumns(),
      listOemRole: [],
      dealerColumns: this.creatHeader4DealerColumns(),
      listDealer: [],
      dealerRoleColumns: this.creatHeader4DealerRoleColumns(),
      listDealerRole: [],
      isSelectColumn: true,
      visibleOemRole: false,
      visibleDealer: false,
      visibleDealerRole: false,
      initDealerData: {},
      initDealerRoleData: {},
      initOemRoleData: {},
      content: '',
      dataMain: {
        caseUrl:[],
        notificationTitle: '',
        status: '',
        orgId: '',
        listDealer: null,
        listDealerRole: null,
        listOemRole: null
      }, // 第一个表单的数据
      dataInfo: null,
      caseUrlList: [],
      caseUrl: null,
      publishType: '',
      isShow: true ,//经销商弹框选择是否选择
      isAdd:false,
      isAddPub:false,
      isReadOnly:this.value.type === 'show'?true:false,
    };
  },
  watch: {
    content(newName, oldName) {
      console.log(newName,'富文本', oldName, );
      //  let  description = newName
      //     description = description.replace(/(\n)/g, "");  
      //     description = description.replace(/(\t)/g, "");  
      //     description = description.replace(/(\r)/g, "");  
      //     description = description.replace(/<\/?[^>]*>/g, "");  
      //     description = description.replace(/\s*/g, "");

      this.dataMain.notificationContent = newName;
    },
    formList(newval,oldval){
      console.log(newval,"newval")
    }
  },
  // 页面加载完成 请求接口
  mounted() {
    this.inputTree();
    if (this.notificationId != null) {
      this.initData();
    }
    if(this.value.type === 'show'){
      this.formList.find(item=>item.fieldName == "endTime").rules=[]
    }
  },
  methods: {
    // 部门树
    async inputTree() {
      let that = []
      const res = await getComOrgTreeList();
      if(this.value.type === 'show'){
        const res2 = await getComOrgTreeLists()
         that = _.uniq(res.data.concat(res2.data))
      }else{
         that = res.data;
      }
      that.forEach(el => (el.text = el.text));
      that.forEach(el => (el.value = el.orgId));
      that.forEach(el => (el.parentId = el.parent));
      this.formList[3].itemList = getJsonTree(that);

      /* if (this.value.type != 'add') {
        this.formList[3].initialValue = `${this.formList.find(item => item.fieldName == 'publishOrgId').initialValue}`;
        console.log(this.formList[3].initialValue, 'this.formList');
      } */
      // this.formList[3].placeholder=this.formList[3].itemList[0].text
      // console.log(this.formList[3].initialValue,this.formList[3].placeholder,"placeholder")
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '公告类别',
          fieldName: 'notificationType',
          placeholder: '请选择',
          itemList: this.createDictList('2561'),
          rules: [{ required: true, message: '请选择公告类别', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '有效期至',
          fieldName: 'endTime',
          dateType:'exactdate',
          placeholder: '请选择',
          initialValue: '',
          rules: [{ required: true, trigger: 'blur', validator: endTime }]
        },
        {
          type: 'SELECT',
          label: '紧急程度',
          fieldName: 'urgency',
          placeholder: '请选择',
          itemList: this.createDictList('2562'),
          rules: [{ required: true, message: '请选择紧急程度', trigger: 'blur' }]
        },
        // {
        //   type: 'INPUT',
        //   label: '通告主题',
        //   fieldName: 'notificationTitle',
        //   placeholder: '请输入',
        //   initialValue: '',
        //   rules: [{ required: true, message: '必填', trigger: 'blur' }, { max: 200, message: '长度最大50字符', trigger: 'blur' }]
        // },
        {
          type: 'INPUT_TREE',
          label: '发布部门',
          fieldName: 'publishOrgId',
          placeholder: '发布部门',
          initialValue: '',
          itemList: [],
          rules: [{ required: true, message: '请选择部门', trigger: 'change' }]
        },
        /* {
          type: 'SELECT',
          label: '全网发布',
          fieldName: 'isAll',
          placeholder: '请选择',
          itemList: this.createDictList('1004'),
          change: this.isAllChange,
          rules: [{ required: true, message: '请选择是否全网发布', trigger: 'change' }]
        } */
      ];
    },

    createFormList1() {
      return [
        {
          type: 'INPUT',
          label: '公告标题',
          fieldName: 'notificationTitle',
          placeholder: '请输入',
          initialValue: '',
          rules: [{ required: true, message: '请输入公告标题', trigger: 'blur' }, { max: 30, message: '长度最大30字符', trigger: 'blur' }]
        }
      ];
    },
    createForm() {
      return [
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          disabled: this.type === 'show' ? true : false,
          fieldName: 'caseUrl',
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 1,
            tipText: '最多上传1个附件',
            fileTypes: ['jpg', 'png','pdf','xls','xlsx','rar','zip']
          }
        }
      ];
    },
    // 车厂角色选择列表
    creatHeader4OemRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.value.type === 'show' ?true:false} onClick={() => this.deleteoemRole(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        // { title: '角色代码', dataIndex: 'roleCode', sorter: true },
        { title: '角色名称', dataIndex: 'roleName', sorter: true }
      ];
    },
    //经销商列表
    creatHeader4DealerColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.value.type === 'show' ?true:false}  onClick={() => this.deleteDealer(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '所属区域', dataIndex: 'saleArea', sorter: true },
        // { title: '经销商代码', dataIndex: 'dealerCode', sorter: true },
        { title: '经销商名称', dataIndex: 'dealerName', sorter: true }
      ];
    },
    //经销商角色类别列表
    creatHeader4DealerRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={this.value.type === 'show' ?true:false} onClick={() => this.deleteDealerRole(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '角色属性',
          dataIndex: 'codeId',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1006'),
          render: props => {
            console.log(props.row.codeId,"props.row")
            return <span>{this.createDictText(props.row.codeId, '1006')}</span>
          }
        }
      ];
    },
    // 角色选择窗口打开 -传数据
    roleHeader() {
      this.initDealerRoleData = {
        id: 1001
      }; //行id
      this.visibleOemRole = true;
    },
    // 角色选择窗口 -返回数据
    closeOemRole(data) {
      console.log('角色选择：', data);
      // this.listOemRole = data.data;
      let OemRoleData = [];
      if(data.data){
        data.data.forEach(x => {
          OemRoleData.push(x);
        });
      }
      
      this.listOemRole = _.uniqBy(this.listOemRole.concat(OemRoleData), 'roleCode');
      this.visibleOemRole = data.visible; //关闭弹窗
    },
    // 经销商选择窗口 -传数据
    dealerHeader() {
      this.initDealerData = {
        excludeBigCustomer: true, // 是否查询大客户经销商，如果查询 true，不查询 false
        id: 1001
      }; //行id
      this.visibleDealer = true;
    },
    // 经销商关闭窗口 -返回数据
    closeDealer(data) {
      console.log('经销商选择：', data);
      // this.listDealer = data.data;
      let Dealer = [];
      if(data.data){
        data.data.forEach(x => {
          Dealer.push(x);
        });
      }
      this.listDealer = _.uniqBy(this.listDealer.concat(Dealer), 'dealerCode');
      this.visibleDealer = data.visible; //关闭弹窗
    },
    // 3 经销商类别选择窗口 -传数据
    dealerRoleHeader() {
      this.initDealerRoleData = {
        id: 1001
      }; //行id
      this.visibleDealerRole = true;
    },
    // 3 经销商角色类别关闭窗口 -返回数据
    closeRoleDealer(data) {
      console.log('经销商角色类别选择：', data);
      // this.listDealerRole = data.data;
      let RoleDealer = [];
      if(data.data){
        data.data.forEach(x => {
          RoleDealer.push({codeId:x.value,codeCnDesc:x.text,index:x.index,$index:x.$index,});
        });
      }
      // console.log(RoleDealer,"RoleDealer")
      this.listDealerRole = _.uniqBy(this.listDealerRole.concat(RoleDealer), 'codeId');
      // console.log(this.listDealerRole,"456")
      this.visibleDealerRole = data.visible; //关闭弹窗
      this.dataMain.listDealerRole=this.listDealerRole
    },
    //发布
    // publishDialog(){
    //   this.publishType = 'publish';
    //   this.$refs.infoMain.SUBMIT_FORM();
    //   this.$refs.infoMain1.SUBMIT_FORM();
    //   this.dataMain.status=25631002
    // },
    publishDialog() {
      let that = this;
      this.publishType = 'publish';
      let infoMainData = this.$refs.infoMain.SUBMIT_FORM();
      this.$refs.infoMain1.SUBMIT_FORM();
      this.dataMain.status = 25631002;
      this.dataMain.endTime = infoMainData.endTime;
      this.dataMain.publishOrgId = infoMainData.publishOrgId;
      this.dataMain.notificationType = infoMainData.notificationType;
      this.dataMain.urgency = infoMainData.urgency;
      this.dataMain.isAll = infoMainData.isAll;
      this.publish();
    },
    //保存
    saveDialog() {
      this.publishType = 'add';
      let infoMainData = this.$refs.infoMain.SUBMIT_FORM();
      this.$refs.infoMain1.SUBMIT_FORM();
      this.dataMain.status = 25631001;
      this.dataMain.orgId = this.dataMain.publishOrgId;
      console.log(this.dataMain, 'this.dataMain', infoMainData);
      this.dataMain.endTime = infoMainData.endTime;
      this.dataMain.publishOrgId = infoMainData.publishOrgId;
      this.dataMain.notificationType = infoMainData.notificationType;
      this.dataMain.urgency = infoMainData.urgency;
      this.dataMain.isAll = infoMainData.isAll;
      if(!this.isAdd){
        this.isAdd=true
        this.submit();
      }
     
    },
    changeHandle(data) {
      this.dataMain = data;
      this.$refs.infoFile.SUBMIT_FORM();
    },
    changeHandle2(data) {
      // console.log(data,"456")
      // this.$refs.infoMain1.SUBMIT_FORM();
      this.dataMain.notificationTitle = data.notificationTitle;
    },
    changeHandleFile(data) {
      console.log(data.caseUrl.length, 'data.caseUrl.length');
      for (let i = 0; i < data.caseUrl.length; i++) {
        this.caseUrlList.push(data.caseUrl[i].url);
      }
      this.dataInfo = this.caseUrlList;
      if (this.publishType === 'add') {
        this.submit();
      } else if (this.publishType === 'publish') {
        this.publish();
      } else if (this.publishType === 'edit') {
        this.update();
      }
    },
    // 关闭当前页面操作
    closeDialog(type) {
      this.$emit('close', { visible: false, type: type });
    },
    deleteDealer(row) {
      this.open(row, this.listDealer, 'dealerTable');
      // this.listDealer.splice(row.$index,1);
      //如果只有一条了清空
      // if(this.listDealer.length == 1){
      //   this.listDealer=[]
      // }
    },
    deleteDealerRole(row) {
      this.open(row, this.listDealerRole, 'dealerRoleTable');
      // this.listDealerRole.splice(row.$index,1);
      // //如果只有一条了清空
      // if(this.listDealerRole.length == 1){
      //   this.listDealerRole=[]
      // }
    },
    deleteoemRole(row) {
      this.open(row, this.listOemRole, 'oemRoleTable');
      // this.listOemRole.splice(row.$index,1);
      //如果只有一条了清空
      // if(this.listOemRole.length == 1){
      //   this.listOemRole=[]
      // }
    },
    // 确定删除
    open(row, data, type2) {
      let that = this;
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // data.splice(row.$index,1);
          let rowArr = [];
          rowArr.push(row);
          this.$refs[type2].EXECUTE_DELETE(rowArr);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    // 数据组装
    async packageData() {
      this.dataMain.notificationContent = this.content;
      this.dataMain.url = this.dataInfo;
      await this.packageListDealer();
      await this.packageListDealerRole();
      // await this.packageListOemROle();
      // console.log("表单1:",this.dataMain);
    },
    // 封装经销商信息
    packageListDealer() {
      var temp = [];
      // console.log("this.listDealer:",this.listDealer);
      if (this.listDealer) {
        if (this.listDealer.length) {
          for (var i = 0; i < this.listDealer.length; i++) {
            var body = {};
            // body.dealerName = this.listDealer[i].dealerShortname;
            // body.ownerCode = this.listDealer[i].dealerCode;
            // body.dealerCompanyId = this.listDealer[i].dealerCompanyId;
            body.dealerName = this.listDealer[i].dealerName;
            body.ownerCode = this.listDealer[i].dealerCode;
            body.saleArea = this.listDealer[i].saleArea;
            temp.push(body);
          }
          console.log(temp,"temp123")
          this.dataMain.listDealer = temp;
        }
      }
    },
    // 封装经销商角色类别信息
    packageListDealerRole() {
      var temp = [];
      // console.log(this.listDealerRole,"this.listDealerRole.length")
      if (this.listDealerRole) {
        for (var i = 0; i < this.listDealerRole.length; i++) {
          var body = {};
          body.codeCnDesc = this.listDealerRole[i].codeCnDesc;
          body.codeId = this.listDealerRole[i].codeId;
          temp.push(body);
        }
        console.log(temp,"temp经销商角色")
        this.dataMain.listDealerRole = temp;
      }
    },
    // 封装车厂角色信息
    /* packageListOemROle() {
      var temp = [];
      // console.log(this.listOemRole,"this.listOemRole")
      if (this.listOemRole) {
        for (var i = 0; i < this.listOemRole.length; i++) {
          var body = {};
          body.roleCode = this.listOemRole[i].roleCode;
          body.roleId = this.listOemRole[i].roleId;
          body.roleName = this.listOemRole[i].roleName;
          temp.push(body);
        }
        // console.log(temp,"temp2")
        this.dataMain.listOemRole = temp;
      }
    }, */
    // 通过ID获取页面详情数据
    async initData() {
      var res = await getNotificationById(this.notificationId);

      if (res.resultCode === 200) {
        this.initPackageData(res);
      } else {
        this.$notify.error({ title: '提示信息', message: res.errMsg || '获取数据异常，请稍后再试！' });
        this.closeDialog();
      }
    },
    // 初始化数据封装
    async initPackageData(res) {
      this.dataMain = res.data;
      // console.log(this.dataMain,"this.dataMain456")
      //赋值
      this.formList.forEach(x => {
        x.initialValue = this.dataMain[x.fieldName];
        if(x.fieldName == 'publishOrgId'){
          x.initialValue = String(this.dataMain[x.fieldName])
        }
      });

      this.content = res.data.notificationContent;
      this.listOemRole = res.data.listOemRole; // TODO 厂端角色获取
      this.dataInfo = res.data.url; // TODO 附件回显
      this.formList1[0].initialValue = this.dataMain.notificationTitle;
      this.formList[1].initialValue = this.dataMain.endTime;
      if(this.dataMain.fileUrl || this.dataMain.fileName){
        this.form[0].initialValue = [{ name: this.dataMain.fileName ? this.dataMain.fileName : '文件下载.xls', url: this.dataMain.fileUrl }];
      }
      // await this.initPackageDealerData(res.data.listDealer); //回显经销商数据
      await this.initPackageDealerRoleData(res.data.listDealerRole); //回显经销商角色类别数据
      // console.log(this.content);
    },
    /* initPackageDealerData(data) {
      if (data) {
        for (var i = 0; i < data.length; i++) {
          var body = {};
          body.dealerShortname = data[i].dealerName;
          body.dealerCode = data[i].ownerCode;
          body.dealerCompanyId = data[i].dealerCompanyId;
          this.listDealer.push(body);
        }
      }
    }, */
    initPackageDealerRoleData(data) {
      console.log(data,"经销商回显data")
      // for (var i = 0; i < data.length; i++) {
      //   var body = {};
      //   body.text = data[i].codeCnDesc;
      //   body.value = data[i].codeId;
      //   this.listDealerRole.push(body);
      // }
      this.listDealerRole=data
      console.log(this.listDealerRole,"经销商回显listDealerRole")
    },
    isAllChange(val) {
      if (val === 10041001) {
        this.isShow = false;
      } else {
        this.isShow = true;
      }
    },

    // 发布
    async publish() {
      this.isAddPub=true
      // this.dataMain.fileUrl = this.form.find(item => item.fieldName == 'caseUrl').initialValue[0].url;
      // this.dataMain.fileName = this.form.find(item => item.fieldName == 'caseUrl').initialValue[0].name;
      if(this.form.find(item=>item.fieldName == "caseUrl").initialValue.length > 0){
        this.dataMain.fileUrl=this.form.find(item=>item.fieldName == "caseUrl").initialValue[0].url
        this.dataMain.fileName=this.form.find(item=>item.fieldName == "caseUrl").initialValue[0].name
      }else{
        this.dataMain.fileUrl=""
        this.dataMain.fileName=""
      }
      await this.packageData();
      if (this.type === 'add') {
        console.log(this.dataMain.listDealerRole, 'this.dataMain.listDealerRole');
        if (this.dataMain.listDealerRole.length > 0) {
          this.$confirm('确定发布?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              publishNotification(this.dataMain, -1).then(res => {
                this.validReturnDate(res);
                this.isAddPub=false
              });
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              });
              this.isAddPub=false
            });
        } else {
          this.$message({
            type: 'info',
            message: '请勾选至少一条经销商角色属性'
          });
          this.isAddPub=false
        }
        // this.validReturnDate(await publishNotification(this.dataMain,-1));
      } else if (this.type === 'edit') {
        this.validReturnDate(await publishNotification(this.dataMain, this.notificationId));
      } else {
        this.validReturnDate(await publishNotification(this.dataMain, -1));
      }
    },
    // 更新
    async update() {
      this.packageData();
      this.validReturnDate(await updateNotification(this.dataMain, this.notificationId));
    },
    // 保存
    async submit() {
      // this.dataMain.fileUrl = this.form.find(item => item.fieldName == 'caseUrl').initialValue[0].url;
      // this.dataMain.fileName = this.form.find(item => item.fieldName == 'caseUrl').initialValue[0].name;
      if(this.form.find(item=>item.fieldName == "caseUrl").initialValue.length > 0){
        this.dataMain.fileUrl=this.form.find(item=>item.fieldName == "caseUrl").initialValue[0].url
        this.dataMain.fileName=this.form.find(item=>item.fieldName == "caseUrl").initialValue[0].name
      }else{
        this.dataMain.fileUrl=""
        this.dataMain.fileName=""
      }
      if (this.value.type != 'add') {
        // console.log(this.dataMain, '编辑保存');
        this.dataMain.notificationContent ? this.dataMain.notificationContent : this.content;
        if (this.dataMain.notificationType && this.dataMain.endTime && this.dataMain.publishOrgId && this.dataMain.notificationTitle && this.dataMain.notificationContent) {
          this.packageData();
          this.validReturnDate(await putNotification(this.dataMain));
        } else {
          this.$notify.error({ title: '提示信息', message: '请填写必填项' });
        }
      } else {
        console.log(this.dataMain, '新增保存');
        this.dataMain.notificationContent ? this.dataMain.notificationContent : this.content;
        if (this.dataMain.notificationType && this.dataMain.endTime && this.dataMain.publishOrgId && this.dataMain.notificationTitle && this.dataMain.notificationContent) {
          if(this.dataMain.listDealerRole){
            if(this.dataMain.listDealerRole.length > 0){
                this.packageData();
                this.validReturnDate(await addNotification(this.dataMain));
            }else{
              this.isAdd=false
              this.$message({
                type: 'info',
                message: '请勾选至少一条经销商角色属性'
              });
            }
          }else{
              this.isAdd=false
              this.$message({
                type: 'info',
                message: '请勾选至少一条经销商角色属性'
              });
            }
          
          
        } else {
          this.$notify.error({ title: '提示信息', message: '请填写必填项' });
        }
      }
    },
    validReturnDate(res) {
      console.log(res, '123');
      if (res.resultCode === 200) {
        this.isAddPub=false
        this.isAdd=false
        this.$notify.success({ title: '提示信息', message: '操作成功!' });
        // 重新加载
        this.closeDialog('refresh');
      } else {
        this.isAddPub=false
        this.isAdd=false
        this.$notify.error({ title: '提示信息', message: res.errMsg });
      }
    }
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
